package cn.stylefeng.guns.sys.modular.dict.config;

import cn.stylefeng.guns.sys.modular.dict.entity.SysDictData;
import cn.stylefeng.guns.sys.modular.dict.entity.SysDictType;
import cn.stylefeng.guns.sys.modular.dict.mapper.SysDictDataMapper;
import cn.stylefeng.guns.sys.modular.dict.mapper.SysDictTypeMapper;
import cn.stylefeng.guns.sys.modular.dict.util.DictUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author S-CH
 * @Date 2024/7/3 15:46
 * @Version 1.0
 */
@Component
public class DictInitConfig implements CommandLineRunner {

    private final SysDictTypeMapper dictTypeMapper;
    private final SysDictDataMapper dictDataMapper;

    @Autowired
    public DictInitConfig(SysDictTypeMapper dictTypeMapper, SysDictDataMapper dictDataMapper) {
        this.dictTypeMapper = dictTypeMapper;
        this.dictDataMapper = dictDataMapper;
    }

    @Override
    public void run(String... args) throws Exception {
        // 查询所有字典类型
        List<SysDictType> dictTypes = dictTypeMapper.selectList(null);

        // 查询所有字典数据
        List<SysDictData> dictData = dictDataMapper.selectList(null);

        // 将字典数据按照类型ID分组，形成树形结构
        Map<Long, List<SysDictData>> dictDataMap = dictData.stream()
                .collect(Collectors.groupingBy(SysDictData::getTypeId));

        // 初始化字典缓存
        DictUtil.init(dictTypes, dictDataMap);
    }
}
